<?php

namespace app\admin\controller\system;

use app\core\exception\ErrorCode;
use app\core\util\ToolUtil;
use think\Request;
use app\base\model\system\SystemMenus as MenusModel;
use app\admin\controller\adminAuthController;

/**
 * 菜单管理控制器
 * Class SystemMenus
 * @package app\admin\controller\system
 */
class SystemMenusController extends adminAuthController
{
    public $bindModel = MenusModel::class;

    protected $needRecordAdminOperationLogAction = ['saveMenu', 'delete'];

    /**
     * 获取菜单列表
     *
     * @return \think\Response
     */
    public function getMenuList()
    {
        $pid = $this->request->param('pid') ? $this->request->param('pid') : 0;
        $params = ToolUtil::getMore([
            ['is_show', ''],
            ['keyword', ''],
            ['pid', $pid]
        ], $this->request);
        $data = MenusModel::getAdminPage($params);
        return $this->successReturn($data);
    }

    /**
     * Desc: 新增或者修改菜单
     * Date: 2019/10/21 21:07
     * Author: yiyu
     * @param Request $request
     * @return \think\response\Json
     */
    public function saveMenu(Request $request)
    {
        $menu_id = input('menu_id');
        $data = ToolUtil::postMore([
            ['menu_pid', 0],
            'menu_icon',
            'menu_name',
            ['module', 'admin'],
            'controller',
            ['action', ''],
            'params',
            ['sort_num', 0],
            ['is_show', 0],
            ['access', 1]
        ], $request);

        if (!$data['menu_name']) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '菜单名称' . ErrorCode::COMMON_MUST_FILL);
        }

        if ($menu_id) {
            if (false === ToolUtil::notIsValidId($menu_id)) {
                return $this->errorReturn(ErrorCode::COMMON_INVALID_PARAMS);
            }

            if (!MenusModel::get($menu_id)) {
                return $this->errorReturn(ErrorCode::DATA_NOT_FOUND);
            }
        }

        if ($menu_id) {
            $data['last_update_admin_id'] = $this->adminId;
            $res = MenusModel::edit($data, $menu_id);
        } else {
            $data['create_admin_id'] = $this->adminId;
            $res = MenusModel::set($data);
        }

        return $res ? $this->successReturn() : $this->errorReturn();
    }

    /**
     * Desc: 删除指定菜单
     * Date: 2019/10/21 21:16
     * Author: yiyu
     * @return \think\response\Json
     */
    public function delete()
    {
        $menu_id = input('menu_id');
        if (!$menu_id) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS);
        }

        if (false === ToolUtil::notIsValidId($menu_id)) {
            return $this->errorReturn(ErrorCode::COMMON_INVALID_PARAMS);
        }

        $res = MenusModel::delMenu($menu_id);
        return $res ? $this->successReturn() : $this->errorReturn();
    }

}
